#include "inc\GUI\audiodialog.h"
#include "ui_audiodialog.h"

#include <QStringBuilder>
#include <QFileInfo>
#include <QFileDialog>
#include <QMessageBox>
#include "actioncommands.h"
#include "history.h"

AudioDialog::AudioDialog(QWidget *parent) :
    EditDialog(parent),
    ui(new Ui::AudioDialog)
{
    ui->setupUi(this);

    ui->buttonBox->addButton(_deleteButton, QDialogButtonBox::DestructiveRole);
    connect(ui->browseBtn, SIGNAL(clicked()), this, SLOT(browseForFile()));

    setContextTip("Sound");
}

AudioDialog::~AudioDialog()
{
    delete ui;
}

void AudioDialog::saveItem(){
    if(_action == NULL){
        //We don't have an action loaded, so this will bring up the
        //new action dialog and create a new action. The dialog is
        //modal, so control should return to this function after the
        //new action is loaded.
        emit needAction();
    }

    SetSoundCommand* command = new SetSoundCommand(_action, _timestamp, ui->filename->text());
    command->execute();
    command->setHistoryTip(tr("Set Sound"));
    History::instance()->push(command);
}

void AudioDialog::deleteItem(){
    //Create a delete key frame command
    DeleteSoundCommand* deleteCommand = new DeleteSoundCommand(_action, _timestamp);
    deleteCommand->setHistoryTip(tr("Delete Sound"));
    deleteCommand->execute();
    History::instance()->push(deleteCommand);
}

void AudioDialog::prepDialog(int msec){
    EditDialog::prepDialog(msec);

    bool exists = false;
    QString filename = "";
    SoundInfo sound;

    if(_action != NULL){
        sound = _action->soundAt(msec);
        if(sound.timestamp != -1){
            filename = *(sound.filename);
            exists = true;
        }
    }

    ui->filename->setText(filename);

    //Set the dialog window title to contain either the sound we are editing
    //or the time where the sound will be inserted.
    QString title = "Edit Sound - ";
    if(exists){
        title += QFileInfo(filename).fileName();
        _deleteButton->setVisible(true);
    }
    else{
        title += QString::number(MSEC_TO_SECF(_timestamp),'f', 2) % "s";
        _deleteButton->setVisible(false);
    }
    this->setWindowTitle(title);
}

void AudioDialog::browseForFile(){
    QString filename = QFileDialog::getOpenFileName(this, tr("Select Audio File"), "", tr("Audio files (*.mp3 *.wav)"));
    ui->filename->setText(filename);
}
